<template>
  <div class="chat-container">
    <h2>聊天室</h2>
    <div class="chat-messages" ref="chatMessages">
      <div
        v-for="message in messages"
        :key="message.id"
        class="message"
        :class="{ sent: message.sender === userId, received: message.sender !== userId }"
      >
        <div class="message-header">
          <span class="sender-name">{{ getUserName(message.sender) }}</span>
          <span class="timestamp">{{ formatTimestamp(message.timestamp) }}</span>
        </div>
        <div class="message-content">
          <div class="text">{{ message.text }}</div>
        </div>
      </div>
    </div>
    <div class="chat-input">
      <input
        v-model="newMessage"
        @keyup.enter="sendMessage"
        placeholder="输入消息..."
        ref="chatInput"
        :disabled="isSending"
      />
      <button @click="sendMessage" :disabled="isSending || newMessage.trim() === ''">
        {{ isSending ? '发送中...' : '发送' }}
      </button>
    </div>
  </div>
</template>
<script>
export default {
  data() {
    return {
      messages: [], // 消息列表
      newMessage: '', // 输入框内容
      websocket: null, // WebSocket 实例
      users: [], // 用户列表
      reconnectCount: 0, // 重连次数计数器
      maxReconnectCount: 5, // 最大重连次数
      isSending: false, // 是否正在发送消息
    };
  },
  computed: {
    // 当前用户 ID
    userId() {
      const userId = this.globalVariable?.userInfoGlobal?.userId || localStorage.getItem('userId');
      if (userId && !localStorage.getItem('userId')) {
        localStorage.setItem('userId', userId);
      }
      return userId;
    },
    // 好友 ID，从路由参数中获取
    friendId() {
      return this.$route.query.friendId || null;
    },
    // 本地存储的键名，用于保存聊天记录
    storageKey() {
      return `chat_history_${this.userId}_${this.friendId}`;
    },
  },
  mounted() {
    this.initUser();
    this.loadChatHistory(); // 加载聊天记录
    this.connectWebSocket(); // 连接 WebSocket
    this.$refs.chatInput.focus(); // 自动聚焦输入框
  },
  beforeDestroy() {
    this.disconnectWebSocket(); // 断开 WebSocket 连接
  },
  methods: {
    // 初始化用户信息
    initUser() {
      const friend = localStorage.getItem('friend');
      if (friend) {
        this.users.push(JSON.parse(friend));
      }
      if (this.globalVariable?.userInfoGlobal) {
        this.users.push(this.globalVariable.userInfoGlobal);
      }
    },
    // 连接 WebSocket
    connectWebSocket() {
      if (!this.userId || !this.friendId) {
        return;
      }
      const wsUrl = `ws://localhost:8160/ws/chat?userId=${this.userId}`;
      this.websocket = new WebSocket(wsUrl);

      this.websocket.onopen = () => {
        console.log('WebSocket 连接已打开');
        this.reconnectCount = 0; // 连接成功，重置重连次数
      };

      this.websocket.onmessage = (event) => {
        console.log('收到消息:', event.data);
        try {
          const message = JSON.parse(event.data);
          // 避免重复添加自己发送的消息
          if (message.sender !== this.userId || !this.messages.some(m => m.id === message.id)) {
            this.addMessage(message); // 添加消息到列表
          }
        } catch (parseError) {
          console.error('解析收到的消息出错:', parseError);
        }
      };

      this.websocket.onerror = (error) => {
        console.error('WebSocket 错误:', error);
      };

      this.websocket.onclose = () => {
        console.log('WebSocket 连接已关闭');
        // 尝试重连
        if (this.reconnectCount < this.maxReconnectCount) {
          this.reconnectCount++;
          setTimeout(() => {
            this.connectWebSocket();
          }, 3000);
        } else {
          console.error('达到最大重连次数，停止重连');
          this.reconnectCount = 0; // 重置计数器
        }
      };
    },
    // 断开 WebSocket 连接
    disconnectWebSocket() {
      if (this.websocket) {
        this.websocket.close();
      }
    },
    // 发送消息
    async sendMessage() {
      if (this.newMessage.trim() === '') return;
      this.isSending = true; // 开始发送

      const message = {
        id: Date.now(), // 生成唯一 ID
        sender: this.userId,
        targetUserId: this.friendId,
        text: this.newMessage,
        timestamp: new Date().toISOString(),
      };

      this.addMessage(message); // 添加消息到列表
      try {
        await this.websocket.send(JSON.stringify(message)); // 通过 WebSocket 发送消息
      } catch (sendError) {
        console.error('发送消息出错:', sendError);
      } finally {
        this.isSending = false; // 发送完成
        this.newMessage = ''; // 清空输入框
        this.$refs.chatInput.focus(); // 自动聚焦输入框
      }
    },
    // 获取用户名
    getUserName(userId) {
      const user = this.users.find((u) => u.userId === userId);
      return user?.nickName || '未知用户';
    },
    // 格式化时间戳
    formatTimestamp(timestamp) {
      const date = new Date(timestamp);
      const hours = String(date.getHours()).padStart(2, '0');
      const minutes = String(date.getMinutes()).padStart(2, '0');
      return `${hours}:${minutes}`;
    },
    // 滚动到底部
    scrollToBottom() {
      this.$nextTick(() => {
        const lastMessage = this.$refs.chatMessages?.lastElementChild;
        if (lastMessage) {
          lastMessage.scrollIntoView({ behavior: 'smooth' });
        }
      });
    },
    // 添加消息到列表
    addMessage(message) {
      this.messages.push(message);
      this.scrollToBottom(); // 滚动到底部
      this.saveChatHistory(); // 保存聊天记录
    },
    // 保存聊天记录到本地存储
    saveChatHistory() {
      try {
        localStorage.setItem(this.storageKey, JSON.stringify(this.messages));
      } catch (storageError) {
        console.error('保存聊天记录到本地存储出错:', storageError);
        alert('保存聊天记录到本地存储出错，请稍后再试');
      }
    },
    // 从本地存储加载聊天记录
    loadChatHistory() {
      try {
        const history = localStorage.getItem(this.storageKey);
        if (history) {
          this.messages = JSON.parse(history);
        }
      } catch (loadError) {
        console.error('从本地存储加载聊天记录出错:', loadError);
        alert('从本地存储加载聊天记录出错，请稍后再试');
      }
    },
  },
};
</script>
<style scoped>
.chat-container {
  padding: 20px;
  max-width: 800px;
  margin: 0 auto;
  border: 1px solid #eee;
  border-radius: 10px;
  box-shadow: 0 0 10px rgba(0, 0, 0, 0.1);
  background-color: #f9f9f9;
}

.chat-messages {
  height: 400px;
  overflow-y: auto;
  padding: 10px;
  border-bottom: 1px solid #eee;
  background-color: #fff;
  border-radius: 8px;
  margin-bottom: 10px;
}

.message {
  margin-bottom: 15px;
  display: flex;
  flex-direction: column;
  max-width: 80%;
}

.message.sent {
  align-items: flex-end;
  margin-left: auto;
}

.message.received {
  align-items: flex-start;
  margin-right: auto;
}

.message-header {
  display: flex;
  align-items: center;
  margin-bottom: 5px;
}

.sender-name {
  font-weight: bold;
  margin-right: 10px;
  font-size: 14px;
  color: #333;
}

.timestamp {
  font-size: 12px;
  color: #888;
}

.message-content .text {
  padding: 10px 15px;
  border-radius: 15px;
  word-wrap: break-word;
  animation: fadeIn 0.3s ease-in-out;
}

.message.sent .text {
  background-color: #42b983;
  color: white;
}

.message.received .text {
  background-color: #f1f1f1;
  color: #333;
}

.chat-input {
  display: flex;
  margin-top: 10px;
}

.chat-input input {
  flex: 1;
  padding: 10px;
  border: 1px solid #eee;
  border-radius: 20px;
  margin-right: 10px;
  outline: none;
  font-size: 14px;
}

.chat-input button {
  background-color: #42b983;
  color: white;
  border: none;
  padding: 10px 20px;
  border-radius: 20px;
  cursor: pointer;
  transition: background-color 0.3s;
  font-size: 14px;
}

.chat-input button:disabled {
  background-color: #ccc;
  cursor: not-allowed;
}

.chat-input button:hover:not(:disabled) {
  background-color: #369f6e;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

/* 自定义滚动条样式 */
.chat-messages::-webkit-scrollbar {
  width: 8px;
}

.chat-messages::-webkit-scrollbar-track {
  background: #f1f1f1;
  border-radius: 4px;
}

.chat-messages::-webkit-scrollbar-thumb {
  background: #ccc;
  border-radius: 4px;
}

.chat-messages::-webkit-scrollbar-thumb:hover {
  background: #999;
}
</style>
